<?php

/**
 * @name StudentController
 * @author ruansheng
 * @desc 学生
 */
class StudentController extends Base {

    public function init() {
        parent::init();
        $this->getView()->assign('active', 2);
    }

    /**
     * http://115.28.74.55:9999/student/index
     * @return bool
     */
	public function indexAction() {
        $p = $this->getRequest()->getRequest('p',1);

        $query = [];
        $fields = [];
        $sort = ['time' => -1];
        $index = 0;
        $limit = 10;

        $Student = new StudentModel();

        // 查询学生数
       $count = $Student->getStudentCount($query);

        // 查询学生列表
       $rows = $Student->getStudentList($query, $fields, $sort, $index, $limit);

        $list = [];
        foreach($rows as $v) {
           $v['_id'] = $v['_id']->__toString();
            $list[] = $v;
        }

        // 计算分页
        $pager = PagerLib::getPager($count, $limit, $p);

        $pagers = $pager['pagers'];

        $this->getView()->assign('list', $list);
        $this->getView()->assign('pagers', $pagers);
        return true;
	}

    /**
     * 添加
     * http://115.28.74.55:9999/class/add
     * @return bool
     */
    public function addAction() {
        if(!$this->getRequest()->isPost()) {
            $this->responseJson(401, '请求方式不正确');
        }

        $data = $this->getRequest()->getRequest();

        $student = new StudentModel();
        $ret = $student->addStudent($data['number'], $data['name'],$data['sex'],$data['password']);
        if($ret[0]) {
            $this->responseJson(200, $ret[1]);
        } else {
            $this->responseJson(401, $ret[1]);
        }
        return false;
    }

    /**
     * 删除
     * http://115.28.74.55:9999/student/delete
     * @return bool
     */
    public function deleteAction() {
        $data = $this->getRequest()->getRequest();

        if(!isset($data['_id'])) {
            $this->responseJson(401, '_id no isset');
        } else if(empty($data['_id'])){
            $this->responseJson(401, '_id is empty');
        }

        $Student = new StudentModel();
        $ret = $Student->deleteStudent($data['_id']);

        if($ret[0]) {
            $this->responseJson(200, $ret[1]);
        } else {
            $this->responseJson(402, $ret[1]);
        }

        return false;
    }

    /**
     * 修改
     * http://115.28.74.55:9999/class/save
     * @return bool
     */
    public function saveAction() {
        if(!$this->getRequest()->isPost()) {
            $this->responseJson(401, '请求方式不正确');
        }

        $data = $this->getRequest()->getRequest();

        $Student = new StudentModel();
        $ret = $Student->saveStudent($data['_id'], $data['number'], $data['name'], $data['sex'], $data['password']);
        if($ret[0]) {
            $this->responseJson(200, $ret[1]);
        } else {
            $this->responseJson(401, $ret[1]);
        }
        return false;
    }
}
